----------------------------------------------------------------------------------------------------------------------------------------------
      name:  <unnamed>
       log:  /Users/ruiyu/Library/CloudStorage/Dropbox/Research/FirmContribution/JMP/Submission/ReStat/Publication/restat_final/output/run-all
> .log
  log type:  text
 opened on:   1 Feb 2026, 10:30:33

. 
. set more off

. set matsize 11000

. set maxvar 30000


. set emptycells drop

. set seed 19911106

. 
. global bin_num 20

. 
. * Set paths
. global code_path ".`c(dirsep)'codes"

. global in_path ".`c(dirsep)'data"

. global out_path ".`c(dirsep)'output"

. global temp_path ".`c(dirsep)'supplement"

. 
. global if_cond "if analysis_sample == 1 & ((ap_sl_cs==1 | ap_sl_cr==1)) & network_node_N < 50"

. 
. ******************************************
. *Define main program. This is what runs. *
. ******************************************
. 
. capture program drop main

. program define main
  1. 
.         run_table_1
  2. 
.         run_table_2
  3. 
.         run_figure_1
  4. 
.         run_figure_2
  5. 
.         run_table_3
  6. 
.         run_table_4
  7. 
.         run_figure_3
  8. 
.         run_table_5
  9. 
. end

. 
. capture program drop run_table_1

. program define run_table_1
  1. 
.         use "${in_path}`c(dirsep)'donor-election_developer-rd.dta", clear
  2. 
.         * Generate contribution recipient category
.         gen recipient = "Winner"    if (contributionamt1 > 0 & !mi(contributionamt1)) ///
>                                      & (mi(contributionamt2) | contributionamt2 <= 0)
  3. 
.         replace recipient = "Runner-up" if (contributionamt2 > 0 & !mi(contributionamt2)) ///
>                                          & (mi(contributionamt1) | contributionamt1 <= 0)
  4. 
.         replace recipient = "Both"      if (contributionamt2 > 0 & !mi(contributionamt2)) ///
>                                          & (contributionamt1 > 0 & !mi(contributionamt1))
  5. 
.         gen tmp = !mi(recipient)
  6. 
.         label variable recipient "Contributing Developers by Mayoral Candidate"
  7.         label variable tmp       "Contributing Developers"
  8. 
.         label def tmp 1 " "
  9.         label value tmp tmp
 10. 
.         tabout tmp recipient if tmp==1 & analysis_sample == 1 ///
>             using ${out_path}`c(dirsep)'tables`c(dirsep)'table_1_firm.tex,  ///
>             c(count tot_cn ///
>               mean tot_cn sd tot_cn ///
>               mean tot_sl_unt_res sd tot_sl_unt_res ///
>               mean tot_sl_val_res sd tot_sl_val_res) ///
>             sum ///
>             h1(Summary Statistics on Developer Contributions to Mayoral Candidates) ///
>             h2(_ Contribution_Amount Housing_Units_Sold Housing_Sales) h2c(1 2 2 2) ///
>             clab(Count Mean SD Mean SD Mean SD) ///
>             font(italic) f(0c 1cm 1cm 1c 1c 1cm 1cm) replace style(tex) label ///
>             fn("Displayed are tabulations and summary statistics ...") replace ///
>             twidth(23) ptotal(none) ntc noborder ///
>             pretext("\documentclass[12pt]{article}\n\usepackage{setspace}\n\begin{document}\n\doublespacing\n") ///
>             posttext("\n\end{document}")
 11. 
.         * --------------------------------------------- *
.         * Load data for summary table
.         * --------------------------------------------- *
.         use "${in_path}`c(dirsep)'election_rd.dta", clear
 12. 
.         * Create election_id if not already present
.         capture confirm variable election_id
 13.         if _rc != 0 {
 14.             gegen election_id = group(election_state election_year election_city)
 15.         }
 16. 
.         * --------------------------------------------- *
.         * Variables & labels needed for summary table
.         * --------------------------------------------- *
. 
.         * Single row category for Mayors
.         gen tmp = 1
 17.         label variable tmp "Mayors"
 18.         label def tmp 1 " "
 19.         label value tmp tmp
 20. 
.         * Column classification: mayor support
.         label variable D_sh_cn_ac_cst "Mayors by Developer Support"
 21.         label def D_sh_cn_ac_cst ///
>             1 "Pro-Development" ///
>             0 "Non-Development"
 22.         label value D_sh_cn_ac_cst D_sh_cn_ac_cst
 23. 
.         * Scaled variables used in table
.         gen sh_cn_wn_cst_1_hd = sh_cn_wn_cst_1 * 100
 24.         gen cn1_th            = cn1 / 1000
 25. 
.         * --------------------------------------------- *
.         * Produce Summary Table
.         * --------------------------------------------- *
. 
.         tabout tmp D_sh_cn_ac_cst ///
>             if !missing(D_sh_cn_ac_cst) ///
>             using ${out_path}`c(dirsep)'tables`c(dirsep)'table_1_city.tex, ///
>             sum c( count tmp ///
>                    mean cn1 sd cn1 ///
>                    mean sh_cn_wn_cst_1_hd sd sh_cn_wn_cst_1_hd ///
>                    mean ptotalunits sd ptotalunits ) ///
>             h1(Summary Statistics on Mayors) ///
>             h2(_ Contributions_from_Developers ///
>                Share_from_Developers Housing_Permits_Issued) ///
>             h2c(1 2 2 2) ///
>             clab(Count Mean SD Mean SD Mean SD) ///
>             f(0c 1cm 1cm 1p 1p 1c 1c) ///
>             replace style(tex) label note("") twidth(14) font(italic) ///
>             longtable ptotal(none) noborder ntc
 26. 
. 
. end

. 
. capture program drop run_table_2

. program define run_table_2
  1. 
.     * ----------------------------------------------------------
.     * Load analysis dataset
.     * ----------------------------------------------------------
.     use "${in_path}`c(dirsep)'donor-election_developer-rd.dta", clear
  2. 
.     * ----------------------------------------------------------
.     * Create election fixed effects if not already present
.     * ----------------------------------------------------------
.     capture confirm variable election_fe_1
  3.     if _rc != 0 quietly tab election_id, gen(election_fe_)
  4. 
.     local m_list 1 2
  5.     local model_label ""
  6. 
.     foreach m in `m_list' {
  7. 
.         local cluster election_id
  8.         local cluster_lab "ELECTION"
  9. 
.         * ------------------------------------------------------
.         * Dependent variable
.         * ------------------------------------------------------
.         if `m' == 1 local dep_var ch_tot_sl_unt_res
 10.         if `m' == 2 local dep_var th_ch_tot_sl_val_res
 11. 
.         * ------------------------------------------------------
.         * FE controls
.         * ------------------------------------------------------
.         local covs covs(election_fe_*)
 12.         local cont_lab "Election FE"
 13. 
.         * ------------------------------------------------------
.         * Label collection
.         * ------------------------------------------------------
.         local lab: variable label `dep_var'
 14.         if "`lab'" == "" local lab `dep_var'
 15.         if `m'==1 local model_label "`"`lab'"'"
 16.         else       local model_label `" `model_label' `"`lab'"' "'
 17. 
.         * ------------------------------------------------------
.         * Clear stored e()
.         * ------------------------------------------------------
.         ereturn clear
 18. 
.         * ------------------------------------------------------
.         * Bandwidth selection (only needed if FE present)
.         * ------------------------------------------------------
.         local bw
 19.         local bs
 20.         local poly_order
 21.         if strpos("`covs'", "_fe_") {
 22.             rdbwselect `dep_var' MV $if_cond, vce(cluster `cluster') masspoints(off)
 23.             local bw h(`e(h_mserd)')
 24.             local bs b(`e(b_mserd)')
 25.             local poly_order p(`e(p)')
 26.         }
 27. 
.         * ------------------------------------------------------
.         * Main RD run
.         * ------------------------------------------------------
.         rdrobust `dep_var' MV $if_cond, vce(cluster `cluster') `bw' `bs' `poly_order' `covs' masspoints(off)
 28. 
.         * ------------------------------------------------------
.         * Store coefficient
.         * ------------------------------------------------------
.         matrix betass = e(b)
 29.         matrix colnames betass = "Pro-Mayor"
 30.         erepost b = betass, rename
 31.         eststo reg_`m'
 32. 
.         * ------------------------------------------------------
.         * Robust p-value
.         * ------------------------------------------------------
.         local robp: di %10.3fc `e(pv_rb)'
 33. 
.         * ------------------------------------------------------
.         * Dependent variable mean
.         * ------------------------------------------------------
.         calc_dep_mean `dep_var' $if_cond
 34.         local out_mean = r(out_mean)
 35. 
.         * ------------------------------------------------------
.         * Number of donors and elections within bandwidth
.         * ------------------------------------------------------
.         quietly distinct election_id firm_id $if_cond & e(sample)==1 & abs(MV)<=e(h_l), joint
 36.         local contributor_N: di %10.0fc r(ndistinct)
 37. 
.         quietly distinct election_id $if_cond & e(sample)==1 & abs(MV)<=e(h_l), joint
 38.         local election_N: di %10.0fc r(ndistinct)
 39. 
.         * ------------------------------------------------------
.         * Bandwidth label for table
.         * ------------------------------------------------------
.         local mv_window_lab = e(h_l)*100
 40.         local mv_window_lab: di %10.1fc `mv_window_lab'
 41. 
.         * ------------------------------------------------------
.         * Attach table statistics
.         * ------------------------------------------------------
.         estadd local list_dep_mean "`out_mean'"
 42.         estadd local list_mv_window "`mv_window_lab'\%"
 43.         estadd local list_eff_N "`contributor_N'"
 44.         estadd local list_ele_N "`election_N'"
 45.         estadd local list_robp `robp'
 46.         estadd local list_cluster `cluster_lab'
 47.         estadd local list_control `cont_lab'
 48.         estadd local list_poly_order `e(p)'
 49.         estadd local list_kernel `e(kernel)'
 50.     }
 51. 
.     * ----------------------------------------------------------
.     * Export table
.     * ----------------------------------------------------------
.     esttab reg_* ///
>         using ${out_path}`c(dirsep)'tables`c(dirsep)'table_2.tex, ///
>         mgroups(`model_label', pattern(1 1) ///
>             prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
>         replace r2 se compress star(* 0.1 ** 0.05 *** 0.01) ///
>         nomtitles label nonotes ///
>         s(list_dep_mean list_robp list_mv_window list_eff_N list_ele_N, ///
>             label("Dep. Var. Mean" "Rob. P-Value" "Optimal Bandwidth" ///
>                   "Donors within Bandwidth" "Elections within Bandwidth"))
 52. end

. 
. capture program drop run_figure_1

. program define run_figure_1
  1. 
.         * ----------------------------------------------------------
.         * Load pre-filtered RD dataset
.         * ----------------------------------------------------------
.         use "${in_path}`c(dirsep)'donor-election_developer-rd.dta", clear
  2. 
.         * ----------------------------------------------------------
.         * Create election fixed effects if not already present
.         * ----------------------------------------------------------
.         capture confirm variable election_fe_1
  3.         if _rc != 0 {
  4.             quietly tab election_id, gen(election_fe_)
  5.         }
  6. 
.         * ----------------------------------------------------------
.         * Prepare covariates list for rdplot
.         * ----------------------------------------------------------
.         ds election_fe_*
  7.         local cov_list `r(varlist)'
  8.         local covs covs(`cov_list')
  9. 
.         * ----------------------------------------------------------
.         * Set dependent variable and cluster
.         * ----------------------------------------------------------
.         local dep_var ch_tot_sl_unt_res
 10.         local cluster election_id
 11.         local graph_name graph_`dep_var'
 12. 
.         * ----------------------------------------------------------
.         * Ensure constant for residualization
.         * ----------------------------------------------------------
.         capture confirm variable tmp_const
 13.         if _rc != 0 gen tmp_const = 1
 14. 
.         * ----------------------------------------------------------
.         * Residualize outcome
.         * ----------------------------------------------------------
.         capture confirm variable r_`dep_var'
 15.         if _rc != 0 {
 16.             quietly reghdfe `dep_var' tmp_const $if_cond, absorb(election_id) residuals(r_`dep_var')
 17.         }
 18. 
.         * ----------------------------------------------------------
.         * Bandwidth selection
.         * ----------------------------------------------------------
.         rdbwselect `dep_var' MV $if_cond, vce(cluster `cluster') masspoints(off)
 19.         local est_bw = e(h_mserd)
 20.         local bw h(`est_bw')
 21.         local bs b(`e(b_mserd)')
 22.         local poly_order p(`e(p)')
 23. 
.         * ----------------------------------------------------------
.         * RD plot to get fitted values
.         * ----------------------------------------------------------
.         rdplot r_`dep_var' MV $if_cond & abs(MV)<=0.2, ///
>             `covs' binselect(qspr) `bw' `bs' `poly_order' masspoints(off) ///
>             graph_options(legend(off) name(`graph_name', replace)) genvars
 24. 
.         * ----------------------------------------------------------
.         * Compute MSE and confidence intervals
.         * ----------------------------------------------------------
.         gen tmp_error_sq = (r_`dep_var' - rdplot_hat_y)^2
 25.         gegen mse = mean(tmp_error_sq)
 26.         gegen mean_x = mean(MV)
 27.         gen tmp_x_err_sq = (MV - mean_x)^2
 28.         gegen tmp_sum_x_err_sq = sum(tmp_x_err_sq)
 29.         gen tmp_N = e(N_l) + e(N_r)
 30.         gen se_yx = sqrt(mse*(1/tmp_N + (tmp_x_err_sq/tmp_sum_x_err_sq)))
 31.         gen ci_ub = rdplot_hat_y + 1.96*se_yx
 32.         gen ci_lb = rdplot_hat_y - 1.96*se_yx
 33.         bys rdplot_id: gen tmp_1 = _n
 34. 
.         * ----------------------------------------------------------
.         * Plot parameters
.         * ----------------------------------------------------------
.         local y_max = 3
 35.         local y_int = 1
 36.         local y_min = -3
 37.         local y_lab_loc = `y_max'*1.15
 38.         local fig_cond "if abs(MV)<=`est_bw'"
 39. 
.         * ----------------------------------------------------------
.         * Final RD figure
.         * ----------------------------------------------------------
.         twoway ///
>             (line rdplot_hat_y MV `fig_cond' & MV>=0, sort lpattern(solid) lwidth(vthick) lcolor(black)) ///
>             (line rdplot_hat_y MV `fig_cond' & MV<0,  sort lpattern(solid) lwidth(vthick) lcolor(black)) ///
>             (scatter rdplot_mean_y rdplot_mean_x $if_cond & tmp_1==1 & abs(MV)<=0.2, sort msymbol(Oh) mcolor(black) msize(medlarge)), ///
>             legend(off) name(`graph_name', replace) ///
>             xtitle("Margin of Victory in Mayoral Election", size(medlarge)) ///
>             xline(0) ///
>             xlabel(-0.2 "-20%" -0.1 "-10%" 0 "0%" 0.1 "10%" 0.2 "20%", labsize(medlarge)) ///
>             ylabel(`y_min'(`y_int')`y_max', format(%9.3gc) labsize(medlarge)) ///
>             yscale(range(`y_min' `y_max')) ///
>             title(" ", size(medlarge)) ///
>             text(`y_max' 0 "Firms Supporting Mayor {&rarr}", size(medlarge) placement(se)) ///
>             text(`y_max' -0.003 "{&larr} Firms Supporting Runner-Up", size(medlarge) placement(sw) justification(right)) ///
>             text(`y_lab_loc' -0.23 "New Housing Units Sold", size(medlarge) placement(ne) justification(right)) ///
>             ysize(10) xsize(16)
 40. 
.         * ----------------------------------------------------------
.         * Export figure
.         * ----------------------------------------------------------
.         graph export "${out_path}`c(dirsep)'figures`c(dirsep)'figure_1.pdf", as(pdf) replace
 41. 
. 
. end // end of program run_figure_1

. 
. capture program drop run_figure_2

. program define run_figure_2
  1. 
.     * ----------------------------------------------------------
.     * Heterogeneity RD Estimate: City Council Approval Required
.     * ----------------------------------------------------------
. 
.     * Load dataset
.     use "${in_path}`c(dirsep)'donor-election_developer-rd.dta", clear
  2. 
.     * Create election fixed effects if not present
.     capture confirm variable election_fe_1
  3.     if _rc != 0 quietly tab election_id, gen(election_fe_)
  4. 
.     * Set dependent variable
.     local dep_var ch_tot_sl_unt_res
  5. 
.     * Cluster and covariates
.     local cluster election_id
  6.     local covs covs(election_fe_*)
  7. 
.     * Heterogeneity: council_byright
.     gen no_council_byright = ~council_byright
  8.     local heterog no_council_byright
  9.     local lab "RD Estimates by Subsamples"
 10. 
.     * ----------------------------------------------------------
.     * Run RD for het = 0 (Not Needed) and het = 1 (Required)
.     * ----------------------------------------------------------
.     foreach set in 0 1 {
 11.         if `set'==0 local cond "${if_cond} & `heterog'==0"
 12.         if `set'==1 local cond "${if_cond} & `heterog'==1"
 13. 
.         * Bandwidth selection
.         rdbwselect `dep_var' MV `cond', vce(cluster `cluster') masspoints(off)
 14.         local bw h(`e(h_mserd)')
 15.         local bs b(`e(b_mserd)')
 16.         local poly_order p(`e(p)')
 17. 
.         * Run RDROBUST
.         rdrobust `dep_var' MV `cond', vce(cluster `cluster') ///
>             `bw' `bs' `poly_order' `covs' masspoints(off)
 18. 
.         * ------------------------------------------------------
.         * Dynamically rename coefficient to match original x-axis
.         * ------------------------------------------------------
.         tempname V
 19.         matrix `V' = e(V)
 20.         matrix `V'[1,1] = e(se_tau_rb)^2
 21.         erepost V=`V'
 22. 
.         matrix betass = e(b)
 23.         matrix colnames betass = "`lab'"   // Sets x-axis label
 24.         erepost b = betass, rename
 25. 
.         * Store estimates
.         eststo reg_`set'_`heterog'
 26.     }
 27. 
.     * ----------------------------------------------------------
.     * Plot coefficients (Not Needed first, Required second)
.     * ----------------------------------------------------------
.     local graph_name Fig_`dep_var'
 28. 
.     coefplot ///
>         (reg_1_`heterog', label("City Council Approval Not Needed") msize(medlarge) msymbol(O) ///
>             ciopts(recast(rcap) lwidth(thick))) ///
>         (reg_0_`heterog', label("City Council Approval Required") msize(medlarge) mcolor(gs16) mlcolor(gs10) ///
>             mlwidth(medthick) msymbol(O) ciopts(recast(rcap) lwidth(thick) lcolor(gs10))), ///
>         ciopts(recast(rcap) lwidth(thick)) vertical ///
>         msize(medlarge) ///
>         mlabel(cond(@pval<.01, "***", cond(@pval<.05, "**", cond(@pval<.1,"*", "")))) ///
>         xtitle(, size(medlarge)) ytitle(, size(medlarge)) ///
>         title("", size(medlarge)) yline(0) xsize(10) ///
>         text(8.5 0.42 "New Housing Units Sold", size(medlarge) placement(ne) justification(right)) ///
>         name(`graph_name', replace) ///
>         ylabel(, format(%8.0gc) labsize(medlarge)) ///
>         graphregion(margin(2 4 2 2)) ///
>         legend( ///
>             ring(0) pos(2) rows(2) ///
>             subtitle("City Council Role in By-Right Developments", size(medlarge)) ///
>             region(fcolor(none)) ///
>             size(medlarge) ///
>         ) ///
>         coeflabels(, labsize(medlarge))
 29. 
.     * Combine graph (layout identical to original)
.     graph combine `graph_name', cols(1) rows(1) title("", size(medlarge)) ///
>         note("") ysize(10) xsize(16)
 30. 
.     * Export plot
.     graph export "${out_path}`c(dirsep)'figures`c(dirsep)'figure_2.pdf", as(pdf) replace
 31. 
.     * Clear estimates
.     eststo clear
 32. 
. end

. 
. capture program drop run_table_3

. program define run_table_3
  1. 
.     * ----------------------------------------------------------
.     * Import cleaned zip–election–year DID dataset
.     * ----------------------------------------------------------
.     use "${in_path}`c(dirsep)'zip-election-year-did.dta", clear
  2. 
.     * ----------------------------------------------------------
.     * Sample restriction
.     * ----------------------------------------------------------
.     local cond "if ((ap_sl_cs==1 | ap_sl_cr==1)) & period>=6 & period<=15"
  3. 
.     * ----------------------------------------------------------
.     * Labels
.     * ----------------------------------------------------------
.     label variable pro_may_ind_post "Connected Zip \times \text{Post}"
  4.     label variable pro_may_ind      "Connected Zip"
  5.     label variable tot_sl_unt_res   "New Housing Units Sold in Zip"
  6. 
.     * ----------------------------------------------------------
.     * Estimation for single outcome variable
.     * ----------------------------------------------------------
.     local dep_var tot_sl_unt_res
  7.     local num = 1
  8. 
.     * Set model label using original logic
.     local lab: variable label `dep_var'
  9.     if "`lab'" == "" {
 10.         local lab `dep_var'
 11.     }
 12.     if `num'==1 {
 13.         local model_label "`"`lab'"'"
 14.     }
 15. 
.     * Loop over FE specifications
.     foreach m in 1 2 3 4 {
 16. 
.         local cluster     city_id
 17.         local cluster_lab "CITY"
 18.         local fe          period_id zip_id
 19.         local fe_lab      ""Period, Zip""
 20. 
.         if `m'==2 {
 21.             local fe     period_id city_id
 22.             local fe_lab ""Period, City""
 23.         }
 24.         if `m'==3 {
 25.             local fe     period_id city_id year
 26.             local fe_lab ""Period, City, Year""
 27.         }
 28.         if `m'==4 {
 29.             local fe     period_id city_id##year
 30.             local fe_lab ""Period, Zip, City \times \text{Year}""
 31.         }
 32. 
.         * Run regression
.         eststo est_`dep_var'_`m': ///
>             reghdfe `dep_var' pro_may_ind_post pro_may_ind Post ///
>             `cond', absorb(`fe') vce(cluster `cluster')
 33. 
.         * --------------------------------------------------
.         * Dependent variable mean
.         * --------------------------------------------------
.         local base_dep_var = subinstr(subinstr("`dep_var'", "fh_", "",.), "th_", "",.)
 34.         summ `base_dep_var' if e(sample)==1 & period==10
 35. 
.         if strpos("`dep_var'","th_") {
 36.             local out_mean = `r(mean)'/1000
 37.         }
 38.         else {
 39.             local out_mean = `r(mean)'
 40.         }
 41.         local out_mean: di %10.2fc `out_mean'
 42. 
.         * --------------------------------------------------
.         * Sample statistics
.         * --------------------------------------------------
.         quietly count if e(sample)==1
 43.         local panel_N: di %10.0fc `r(N)'
 44. 
.         quietly gdistinct election_id zip_id if e(sample)==1, joint
 45.         local Zip_N: di %10.0fc r(ndistinct)
 46. 
.         quietly gdistinct election_id if e(sample)==1, joint
 47.         local election_N: di %10.0fc r(ndistinct)
 48. 
.         * Store table stats
.         quietly estadd local list_dep_mean "`out_mean'"
 49.         quietly estadd local list_panel_N  "`panel_N'"
 50.         quietly estadd local list_zip_N    "`Zip_N'"
 51.         quietly estadd local list_ele_N    "`election_N'"
 52.         quietly estadd local list_cluster  `cluster_lab'
 53.         quietly estadd local list_fe       `fe_lab'
 54.     }
 55. 
.     * ----------------------------------------------------------
.     * Table output
.     * ----------------------------------------------------------
.     esttab est* ///
>         using ${out_path}`c(dirsep)'tables`c(dirsep)'table_3.tex, ///
>         keep(pro_may_ind_post) ///
>         mgroups(`model_label', pattern(1 0 0 0) ///
>             prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
>         replace r2 se compress star(* 0.1 ** 0.05 *** 0.01) ///
>         nomtitles label nonotes ///
>         s(list_dep_mean list_fe list_zip_N list_ele_N, ///
>             label("Dep. Var. Mean" "Fixed Effects" "Zip Codes" "Mayoral Elections")) ///
>         addnote("") ///
>         interaction(" $\times$ ")
 56. 
. end

. 
. capture program drop run_table_4

. program define run_table_4
  1. 
.     * ----------------------------------------------------------
.         * Import city-level RD dataset
.         * ----------------------------------------------------------
.         use "${in_path}`c(dirsep)'election_rd.dta", clear
  2. 
.         * ----------------------------------------------------------
.         * Sample restriction and FE setup
.         * ----------------------------------------------------------
.         gen _const = 1
  3.         local cond "if sample_firm_rd==1" 
  4. 
.         * CBSA FE
.         quietly: tab cbsa_id, gen(cbsa_fe_)
  5.         local covs covs(cbsa_fe_*)
  6.         local cont_lab "CBSA FE"
  7.         local cluster "cluster cbsa_id"
  8.         local cluster_lab "CBSA"
  9. 
.         * ----------------------------------------------------------
.         * Labels
.         * ----------------------------------------------------------
.         label variable tot_sl_unt_res "New Housing Units Sold, Citywide"
 10.         label variable const1 "Developer Donors"
 11. 
.         * ----------------------------------------------------------
.         * Loop over dependent variables
.         * ----------------------------------------------------------
.         local dep_vars const1 tot_sl_unt_res ptotalunits 
 12.         local model_label ""
 13.         eststo clear
 14. 
.         local coef_tot_sl_unt_res .
 15.         local coef_ptotalunits .
 16. 
.         foreach dep_var of local dep_vars {
 17. 
.             * Set model label using original logic
.             local lab: variable label `dep_var'
 18.             if "`lab'" == "" local lab `dep_var'
 19.             local model_label `" `model_label' `"`lab'"'"'
 20. 
.             * ------------------------------------------------------
.             * Run RD regression
.             * ------------------------------------------------------
.             rdrobust `dep_var' MV_sh_cn_ac_cst `cond', vce(`cluster') `covs'
 21.             
.             * Store coefficient for table
.             matrix betass = e(b)
 22.             matrix colnames betass = "Pro-Dev"
 23.             erepost b = betass, rename
 24. 
.             * Capture coefficients as locals
.             if "`dep_var'" == "const1" {
 25.                 matrix b = e(b)
 26.                 local Ndiff = b[1,1]
 27.                 local Ndiff_fmt: display %10.2f `Ndiff'
 28.             }
 29. 
.             if "`dep_var'" == "tot_sl_unt_res" {
 30.                 matrix b = e(b)
 31.                 local coef_tot_sl_unt_res = b[1,1]
 32. 
.                 }
 33. 
.             if "`dep_var'" == "ptotalunits" {
 34.                 matrix b = e(b)
 35.                 local coef_ptotalunits = b[1,1]
 36.                 eststo r_`dep_var'
 37. 
.                 * ----------------------------------------------------------
.                         * Compute Permit/Sales Ratio lambda
.                         * ----------------------------------------------------------
.                         local lambda_ratio = `coef_tot_sl_unt_res'/`coef_ptotalunits'
 38.                         local lambda_ratio_fmt: display %10.2f `lambda_ratio'
 39.                 
.                 * Attach formatted Ndiff coefficient
.                 estadd local Ndiff `Ndiff_fmt'
 40.                 estadd local PermitSalesRatio `lambda_ratio_fmt'
 41.             }
 42. 
.             * ------------------------------------------------------
.             * Dependent variable mean
.             * ------------------------------------------------------
.             local base_dep_var = subinstr(subinstr("`dep_var'", "fh_", "",.), "th_", "",.)
 43.             summ `base_dep_var' if e(sample)==1 & abs(MV_sh_cn_ac_cst) <= e(h_r)
 44. 
.             if strpos("`dep_var'","th_") {
 45.                 local out_mean = `r(mean)'/1000
 46.             }
 47.             else local out_mean = `r(mean)'
 48.             local out_mean: di %10.2fc `out_mean'
 49. 
.             * ------------------------------------------------------
.             * Count elections within bandwidth
.             * ------------------------------------------------------
.             quietly: distinct election_id if e(sample)==1 & abs(MV_sh_cn_ac_cst) <= e(h_r)
 50.             local election_N: di %10.0fc r(ndistinct)
 51. 
.             * Record optimal bandwidth and robust p-value
.             local mv_window_lab = e(h_l)*100
 52.             local mv_window_lab: di %10.1fc `mv_window_lab'
 53.             local robp: di %10.3fc `e(pv_rb)'
 54. 
.             * ------------------------------------------------------
.             * Add locals for esttab
.             * ------------------------------------------------------
.             quietly: estadd local list_dep_mean "`out_mean'"
 55.             quietly: estadd local list_mv_window "`mv_window_lab'\%"
 56.             quietly: estadd local list_ele_N "`election_N'"
 57.             quietly: estadd local list_poly_order `e(p)'
 58.             quietly: estadd local list_kernel `e(kernel)'
 59.             quietly: estadd local list_cluster `cluster_lab'
 60.             quietly: estadd local list_control `cont_lab'
 61.             quietly: estadd local list_robp `robp'
 62.         }
 63. 
.         * ----------------------------------------------------------
.         * Table output
.         * ----------------------------------------------------------
.         esttab r_* ///
>             using ${out_path}`c(dirsep)'tables`c(dirsep)'table_4.tex, ///
>             mgroups("Housing Permits", pattern(1) ///
>                 prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
>             replace r2 se compress star(* 0.1 ** 0.05 *** 0.01) ///
>             nomtitles label nonotes ///
>             s(list_dep_mean list_robp list_mv_window list_ele_N Ndiff PermitSalesRatio, ///
>               label("Dep. Var. Mean" "Rob. P-value" "Optimal Bandwidth" "Elections within Bandwidth" "{\$N^{DEV}-N^{NON}\$}" "Permit/Sales R
> atio ($\lambda$)")) ///
>             addnote("")
 64. 
. end

. 
. capture program drop run_figure_3

. program define run_figure_3
  1. 
.     *-----------------------------------------------
.     * Load slimmed election-level data
.     *-----------------------------------------------
.     use "$in_path`c(dirsep)'election_rd.dta", clear
  2. 
.     *-----------------------------------------------
.     * Ensure CBSA FE exists
.     *-----------------------------------------------
.     capture confirm variable cbsa_fe_1
  3.     if _rc != 0 {
  4.         quietly: tab cbsa_id, gen(cbsa_fe_)
  5.     }
  6.     local covs covs(cbsa_fe_*)
  7. 
.     *-----------------------------------------------
.     * Ensure sample indicator exists
.     *-----------------------------------------------
.     capture confirm variable sample_firm_rd
  8.     if _rc {
  9.         gen sample_firm_rd = 1
 10.     }
 11. 
.     *-----------------------------------------------
.     * Generate residuals for plotting
.     *-----------------------------------------------
.     local dep_var ptotalunits
 12.     capture confirm variable r_`dep_var'
 13.     if _rc != 0 {
 14.         gen tmp_const = 1
 15.         quietly: reghdfe `dep_var' tmp_const, absorb(cbsa_id) residuals(r_`dep_var')
 16.     }
 17. 
.     *-----------------------------------------------
.     * Run RD estimate (covariates included if available)
.     *-----------------------------------------------
.     local cond "if sample_firm_rd==1"
 18.     local cluster "cluster cbsa_id"
 19. 
.     local cmd "rdrobust `dep_var' MV_sh_cn_ac_cst `cond', vce(`cluster') `covs'"
 20.     di "`cmd'"
 21.     `cmd'
 22. 
.     local est_bw = `e(h_l)'
 23.     local bw h(`est_bw')
 24.     local bs b(`e(b_l)')
 25.     local poly_order p(`e(p)')
 26. 
.     *-----------------------------------------------
.     * Set plot parameters
.     *-----------------------------------------------
.     local y_max = 5000
 27.     local y_min = -5000
 28.     local y_int = 2500
 29.     local y_lab_loc = `y_max'*1.15
 30.     local lab_title: variable label `dep_var'
 31.     local graph_name graph_`dep_var'
 32. 
.         local fig_cond "`cond' & abs(MV_sh_cn_ac_cst )<=`est_bw'"
 33. 
.     *-----------------------------------------------
.     * Generate RD plot
.     *-----------------------------------------------
.     rdplot r_`dep_var' MV_sh_cn_ac_cst `cond', ///
>         binselect(qsmvpr) `covs' `bw' `bs' `poly_order' ///
>         graph_options(legend(off) ///
>             title("`lab_title'", size(large)) ///
>             xtitle("Margin of Victory of Pro-Dev Mayor", size(large)) ///
>             xlabel(, format(%9.3gc) labsize(large)) ///
>             yscale(range(`y_min' `y_max')) ///
>             ylabel(`y_min'(`y_int')`y_max', format(%9.3gc) labsize(large)) ///
>             name(`graph_name', replace)) genvars
 34. 
.     *-----------------------------------------------
.     * Compute SE bands manually
.     *-----------------------------------------------
.     gen tmp_error_sq = (r_`dep_var' - rdplot_hat_y)^2
 35.     gegen mse = mean(tmp_error_sq)
 36.     gegen mean_x = mean(MV_sh_cn_ac_cst)
 37.     gen tmp_x_err_sq = (MV_sh_cn_ac_cst - mean_x)^2
 38.     gegen tmp_sum_x_err_sq = sum(tmp_x_err_sq)
 39.     gen tmp_N = e(N_l) + e(N_r)
 40.     gen se_yx = sqrt(mse * (1/tmp_N + (tmp_x_err_sq / tmp_sum_x_err_sq)))
 41.     gen ci_ub = rdplot_hat_y + 1.96 * se_yx
 42.     gen ci_lb = rdplot_hat_y - 1.96 * se_yx
 43.     bys rdplot_id: gen tmp_1 = _n
 44. 
.     *-----------------------------------------------
.     * Plot
.     *-----------------------------------------------
.     twoway ///
>         (line rdplot_hat_y MV_sh_cn_ac_cst `fig_cond' & MV_sh_cn_ac_cst >=0, ///
>             sort lpattern(solid) lwidth(vthick) lcolor(black)) ///
>         (line rdplot_hat_y MV_sh_cn_ac_cst `fig_cond' & MV_sh_cn_ac_cst <0, ///
>             sort lpattern(solid) lwidth(vthick) lcolor(black)) ///
>         (scatter rdplot_mean_y rdplot_mean_x `cond' & tmp_1==1 & abs(MV_sh_cn_ac_cst) <= 0.1, ///
>             sort msymbol(Oh) mcolor(black) msize(medlarge)), ///
>         legend(off) name(`graph_name', replace) ///
>         xtitle("Margin of Victory of Pro-Dev Mayor", size(medlarge)) ///
>         xlabel(-0.1 "-10%" -0.05 "-5%" 0 "0%" 0.05 "5%" 0.1 "10%", labsize(medlarge)) ///
>         xline(0) xlabel(, labsize(medlarge)) ///
>         title(" ", size(medlarge)) ///
>         ylabel(`y_min'(`y_int')`y_max', format(%9.3gc) labsize(medlarge)) ///
>         yscale(range(`y_min' `y_max')) ///
>         text(`y_max' 0 "Cities with Pro-Dev Mayor {&rarr}", size(medlarge) placement(ne)) ///
>         text(`y_max' -0.001 "{&larr} Cities with Non-Dev Mayor", size(medlarge) placement(nw) justification(right)) ///
>         text(`y_lab_loc' -0.135 "Housing Permits Issued", size(medlarge) placement(ne) justification(right)) ///
>         ysize(10) xsize(16)
 45. 
.     *-----------------------------------------------
.     * Export figure
.     *-----------------------------------------------
.         * Display graph before exporting
.         graph display `graph_name'
 46. 
.         * Attempt PDF export (capture to avoid stopping)
.         graph export "${out_path}`c(dirsep)'figures`c(dirsep)'figure_3.pdf", as(pdf) replace
 47. 
. end

. 
. capture program drop run_table_5

. program define run_table_5
  1. 
.         *------------------------------------------------------------
.         * Globals: Table 5 values (numeric)
.         *------------------------------------------------------------
.         global T5_beta      2.044
  2.         global T5_B         2124
  3.         global T5_lambda    2.47
  4.         global T5_Ndiff     39.37
  5. 
.         *------------------------------------------------------------
.         * Compute share
.         *------------------------------------------------------------
.         scalar T5_share_num = ///
>             (${T5_beta} * ${T5_lambda} * ${T5_Ndiff}) / ${T5_B}
  6. 
.         * format as percentage with one decimal
.         global T5_share : display %9.1f (100 * T5_share_num)
  7.         global T5_share "${T5_share}\%"
  8. 
.         *------------------------------------------------------------
.         * Create Table 5 (tabularx) LaTeX child document
.         *------------------------------------------------------------
.         local outfile "/Users/ruiyu/Library/CloudStorage/Dropbox/Research/FirmContribution/JMP/Submission/ReStat/Publication/restat_final/ou
> tput/tables/table_5.tex"
  9. 
.         file open fh using "`outfile'", write replace text
 10. 
.         file write fh "\begin{tabularx}{\textwidth}" _n
 11.         file write fh "{>{\raggedleft\arraybackslash}X" _n
 12.         file write fh " >{\raggedleft\arraybackslash}p{0.5cm}" _n
 13.         file write fh " >{\centering\arraybackslash}p{2.5cm}" _n
 14.         file write fh " >{\centering\arraybackslash}p{1.5cm}}" _n
 15.         file write fh "\hline" _n
 16.         file write fh "\textbf{\footnotesize Description} &  & \textbf{\footnotesize Parameter} & \textbf{\footnotesize Estimate} \\\\" _
> n
 17.         file write fh "\hline" _n
 18. 
.         file write fh "{\footnotesize Impact of Connection to Mayor on Developer Sales of New Housing Units}" ///
>                       " &  & {\footnotesize \$\beta\$} & {\footnotesize ${T5_beta}} \\\\" _n
 19.         file write fh _n
 20. 
.         file write fh "{\footnotesize Impact of Electing Pro-Development Mayor on Housing Permits}" ///
>                       " &  & {\footnotesize \$B\$} & {\footnotesize ${T5_B}} \\\\" _n
 21.         file write fh _n
 22. 
.         file write fh "{\footnotesize Factor Adjusting Sales of New Housing Units into New Housing Permits}" ///
>                       " &  & {\footnotesize \$\lambda\$} & {\footnotesize ${T5_lambda}} \\\\" _n
 23.         file write fh _n
 24. 
.         file write fh "{\footnotesize Number of Developers Connected to Pro-Development Mayor minus Opponent Candidate}" ///
>                       " &  & {\footnotesize \$N^{DEV}-N^{NON}\$} & {\footnotesize ${T5_Ndiff}} \\\\" _n
 25. 
.         file write fh "\hline" _n
 26. 
.         file write fh "{\footnotesize Share of Housing Supply Impact Attributed to Favors from Pro-Development Mayors}" ///
>                       " &  & {\footnotesize \$\frac{(N^{DEV}-N^{NON})\times\lambda\times\beta}{B}\$}" ///
>                       " & {\footnotesize ${T5_share}} \\\\" _n
 27. 
.         file write fh "\hline" _n
 28.         file write fh "\end{tabularx}" _n
 29. 
.         file close fh
 30. 
.         display as text "Table written to: `outfile'"
 31. 
. 
. 
. end

. 
. capture program drop calc_dep_mean

. program define calc_dep_mean, rclass
  1. args dep_var
  2. 
.         local base_dep_var = subinstr(subinstr(subinstr("`dep_var'", "fh_", "",.), "th_", "",.), "ch_", "", .)
  3. 
.         bys firm_id election_id: gegen tmp_max = max(e(sample))
  4.         summ `base_dep_var' if tmp_max==1 & MV<0 & abs(MV)<=e(h_l) //& period==0 
  5. 
.         * Normalize to thousands
.         if strpos("`dep_var'","th_") {
  6.                 local dep_mean = `r(mean)'/1000
  7.         }
  8.         else {
  9.                 local dep_mean = `r(mean)'
 10.         }
 11.         drop tmp*
 12.         local dep_mean: di %10.2fc `dep_mean'
 13.         return scalar out_mean = `dep_mean'
 14. 
. end

. 
. cap log close
